package com.xyhuo.leetcode.december;

/**
 * 删除有序数组中的重复项Ⅱ
 * https://leetcode.cn/problems/remove-duplicates-from-sorted-array-ii/
 *
 * @time 2023/12/29
 */
public class RemoveDuplicates2 {

//    public static void main(String[] args) {
//        RemoveDuplicates2 rd = new RemoveDuplicates2();
//        int[] nums = {1, 1, 1, 1, 2, 2, 2, 3, 4};
//        rd.removeDuplicates(nums);
//    }

    public int removeDuplicates(int[] nums) {
        if (nums.length < 3) {
            return nums.length;
        }
        int leftIndex = 0, rightIndex = 0;
        while (rightIndex < nums.length) {
            int tmp = rightIndex;
            while (rightIndex + 1 < nums.length && nums[rightIndex + 1] == nums[tmp]) {
                rightIndex++;
            }
            if (tmp != rightIndex) {
                nums[leftIndex] = nums[tmp];
                nums[leftIndex + 1] = nums[tmp];
                leftIndex += 2;
            } else {
                nums[leftIndex] = nums[tmp];
                leftIndex++;
            }
            rightIndex++;
        }
        return leftIndex;
    }
}
